package org.doubango.ngn.utils

import org.doubango.ngn.NgnApplication
import java.io.IOException
import java.lang.ref.WeakReference

class AudioTipUtil {

    companion object {
        private var startTalkTipBytesCache: WeakReference<ByteArray?>? = null
        private var stopTalkTipBytesCache: WeakReference<ByteArray?>? = null

        fun getStartTalkTipBytes(): ByteArray? {
            var bytes = startTalkTipBytesCache?.get()
            if (bytes == null) {
                bytes = readPCM2Bytes("start.pcm")
                startTalkTipBytesCache = WeakReference(bytes)
            }
            return bytes
        }

        fun getStopTalkTipBytes(): ByteArray? {
            var bytes = stopTalkTipBytesCache?.get()
            if (bytes == null) {
                bytes = readPCM2Bytes("stop.pcm")
                stopTalkTipBytesCache = WeakReference(bytes)
            }
            return bytes
        }

        private fun readPCM2Bytes(fileName: String): ByteArray? {
            try {
                val assets = NgnApplication.getContext().assets
                assets.open(fileName).use { input ->
                    return input.readBytes()
                }
            } catch (e: IOException) {
                e.printStackTrace()
                return null
            }
        }
    }

}